package models.base;

import facade.AppContext;
import models.common.BaseModel;
import models.constants.DeletedStatus;
import org.apache.commons.lang.StringUtils;

import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import java.util.Date;
import java.util.List;

/**
 * Created by weiwei on 2018/02/08.
 */
@Entity
@Table(name = "admin_user_roles")
public class AdminUserRole extends BaseModel {

    /**
     * 用户
     */
    @ManyToOne
    @JoinColumn(name = "user_id")
    public AdminUser user;

    /**
     * 角色
     */
    @ManyToOne
    @JoinColumn(name = "role_id")
    public Role role;

    /**
     * 删除用户角色
     * @param userId
     */
    public static void deleteByUserId(String userId){
        AdminUser loginUser = AppContext.currentUser();
        AdminUserRole userRole = findByUserId( userId );
        if(userRole != null){
            userRole.deleted = DeletedStatus.DELETED;
            userRole.modifyAt = new Date();
            userRole.modifyUser = loginUser;
            userRole.save();
        }
    }

    /**
     * 查询有多少用户拥有的该角色
     * @param roleId
     * @return
     */
    public static Long countByRole(String roleId){
        return count("deleted=? and role.id=?", DeletedStatus.UN_DELETED,roleId);
    }

    /**
     * 查询用户角色
     * @param userId
     * @return
     */
    public static AdminUserRole findByUserId(String userId){
        if(StringUtils.isEmpty(userId)) return null;
        List<AdminUserRole> roleList = find(" deleted=?",DeletedStatus.UN_DELETED).fetch();
        return find(" user.id = ? and  deleted = ?", userId, DeletedStatus.UN_DELETED).first();
    }



}
